﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    struct GamePictureBoxTemplate
    {
        public int Row, Col;
    }

    class GamePictureBox : PictureBox
    {
        public static MainForm mainForm { set; get; }

        private static GamePictureBoxTemplate template = new GamePictureBoxTemplate() { Row = 4, Col = 4 };

        public int Id { set;  get; }

        public static GamePictureBox NewInstance(int id, int x, int y, bool empty = false)
        {
            var func = ImgManager.GenPart(template.Row, template.Col);

            int ux = ImgManager.Img.Width / template.Row, uy = ImgManager.Img.Height / template.Col;

            return new GamePictureBox()
            {
                Id = empty ? -id : id,
                Width = ux,
                Height = uy,
                Image = empty ? new Bitmap(ux, uy) : func(x, y),
                SizeMode = PictureBoxSizeMode.StretchImage,
                Location = new Point(x * ux, y * uy),
                BorderStyle = BorderStyle.FixedSingle,
                AllowDrop = true,
            };
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            if (e.Button == MouseButtons.Left)
            {
                DoDragDrop(this, DragDropEffects.Move);
            }
        }

        protected override void OnDragOver(DragEventArgs drgevent)
        {
            base.OnDragOver(drgevent);

            if (drgevent.Data.GetDataPresent(typeof(GamePictureBox)))
            {
                drgevent.Effect = DragDropEffects.Move;
            }
        }

        protected override void OnDragEnter(DragEventArgs drgevent)
        {
            base.OnDragEnter(drgevent);

            if(drgevent.Data.GetDataPresent(typeof(GamePictureBox))) 
            {
                drgevent.Effect = DragDropEffects.Move;
            }
        }

        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            base.OnDragDrop(drgevent);

            GamePictureBox box = (GamePictureBox) drgevent.Data.GetData(typeof(GamePictureBox));

            swap(box);

            if(mainForm.check())
            {
                DialogResult dr = MessageBox.Show("恭喜你完成了拼图！继续？", "", MessageBoxButtons.OKCancel);

                if (dr == DialogResult.OK)
                {
                    mainForm.reset();
                }
            }
        }

        public void swap(GamePictureBox b)
        {
            Image t = Image; Image = b.Image; b.Image = t;

            int tt = Id; Id = b.Id; b.Id = tt;
        }
    }
}
